package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"net/url"
	"strconv"
	"time"
	"xianzhi/models"
	"xianzhi/service"
	"xianzhi/utils"
)

type CommonController struct {
	beego.Controller
}

// 根据上级区域id获取其下级区域
func (c *CommonController) GetRegionListByParent() {
	id := utils.Atoi64(c.GetString("id"))
	level, _ := strconv.Atoi(c.GetString("level"))
	c.Data["levelShow"] = "请选择" + models.RegionLevel[level]
	if id > 0 {
		c.Data["regionList"] = service.GetRegionListByParent(id)
	}
	c.TplName = "common/option-region.html"
}

// 发送手机验证码
func (c *CommonController) SendMobileMsg() {
	var res *utils.ResJsonStruct
	ip := c.Ctx.Input.IP()
	mobile := c.GetString("mobile")
	if len(mobile) <= 0 {
		res = utils.ResJson(0, "请输入手机号", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if !utils.IsMobile(mobile) {
		res = utils.ResJson(0, "请输入正确的手机号", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	currentTime := time.Now().Unix()
	p := map[string]interface{}{}
	p["ip"] = ip
	ipVerifyCode := service.GetVerifyCodeInfo(p)
	if ipVerifyCode.Id > 0 {
		allowTime := ipVerifyCode.SendTime.Add(1 * time.Minute).Unix()
		if allowTime > currentTime { // 距离上次发送1分钟之内，不允许发送
			res = utils.ResJson(0, "操作过于频繁，请稍候再进行操作", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}
	}

	code := utils.GenVerifyCode()
	p = map[string]interface{}{}
	p["key"] = mobile
	keyVerifyCode := service.GetVerifyCodeInfo(p)
	if keyVerifyCode.Id > 0 {
		allowTime := keyVerifyCode.SendTime.Add(1 * time.Minute).Unix()
		if allowTime > currentTime { // 距离上次发送1分钟之内，不允许发送
			res = utils.ResJson(0, "操作过于频繁，请稍候再进行操作", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}

		sendMobileMsgRes := utils.SendMobileMessage([]string{mobile}, "523799", []string{code})
		if !sendMobileMsgRes {
			res = utils.ResJson(0, "验证码发送失败", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}

		count := keyVerifyCode.Count + 1
		editInput := url.Values{
			"id": {fmt.Sprintf("%d", keyVerifyCode.Id)},
			"ip": {ip},
			"code": {code},
			"count": {fmt.Sprintf("%d", count)},
		}
		service.EditVerifyCode(editInput)

		res = utils.ResJson(0, "验证码发送成功，请注意查收", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	sendMobileMsgRes := utils.SendMobileMessage([]string{mobile}, "523799", []string{code})
	if !sendMobileMsgRes {
		res = utils.ResJson(0, "验证码发送失败", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	addInput := url.Values{
		"ip": {ip},
		"key": {mobile},
		"code": {code},
		"count": {"1"},
	}
	service.AddVerifyCode(addInput)

	res = utils.ResJson(0, "短信发送成功，请注意查收", "")
	c.Data["json"] = res
	c.ServeJSON()
	return
}
